# coding = utf-8
# File date: Hi_2022/11/15 22:05
# File_name: keyboard_package.py
import time
from pynput.keyboard import Key
import pynput
from tkinter import END
from tkinter.scrolledtext import ScrolledText
from GUI_log import log_out

# 日志初始化
g_log = log_out()


class keyboard_method:
    def __init__(self):
        # 键盘实例化
        self.keyboard = pynput.keyboard.Controller()
        g_log.success("键盘实例化")

    def keyboard_press(self, key: Key, sleep_time: float):
        """
        :param key: 要点击的按键
        :param sleep_time: 动作间隔时间,会先在执行动作前休眠此事件再执行
        :return: 无返回,按下指定按键
        """
        g_log.info(f"执行键盘{key}按下前先休眠{sleep_time}秒")
        time.sleep(sleep_time)
        self.keyboard.press(key)
        g_log.success(f"执行键盘{key}按下完成")

    @staticmethod
    def write_key_press(text: ScrolledText, key: str, sleep_time: float):
        """
        :param text: 需要写入的滚动文本框
        :param key: 需要按下的按键,需要转换成字符串
        :param sleep_time: 动作间隔时间,会先在执行动作前休眠此事件再执行
        :return: 向滚动文本框最后写入调用keyboard_press方法的字符串
        """
        text.insert(END, f"keyboard_press({key}, {sleep_time})\n")
        g_log.success(f"keyboard_press({key}, {sleep_time}) 插入滚动文本框")

    def keyboard_release(self, key: Key, sleep_time: float):
        """
        :param key: 要点击的按键
        :param sleep_time: 动作间隔时间,会先在执行动作前休眠此事件再执行
        :return: 无返回,松开指定按键
        """
        g_log.info(f"执行键盘{key}释放前先休眠{sleep_time}秒")
        time.sleep(sleep_time)
        self.keyboard.release(key)
        g_log.success(f"执行键盘{key}释放完成")

    @staticmethod
    def write_key_release(text: ScrolledText, key: str, sleep_time: float):
        """
        :param text: 需要写入的滚动文本框
        :param key: 需要松开的按键,需要转换成字符串
        :param sleep_time: 动作间隔时间,会先在执行动作前休眠此事件再执行
        :return: 向滚动文本框最后写入调用keyboard_release方法的字符串
        """
        text.insert(END, f"keyboard_release({key}, {sleep_time})\n")
        g_log.success(f"keyboard_release({key}, {sleep_time}) 插入滚动文本框")
